//发送Get请求
const https = require("https");
const http = require("http");

export function get(options: Object, callback: Function): void {
  //创建请求
  let data = "";
  let req = http.request(options, function (res) {
    console.log("STATUS:" + res.statusCode);
    console.log("HEADERS:" + JSON.stringify(res.headers));
    res.setEncoding("utf-8");
    res.on("data", function (chunk) {
      // console.log('数据片段分隔-----------------------\r\n');
      // console.log(chunk);

      data += chunk;
    });
    res.on("end", function (chunk) {
      callback(chunk);
      console.log("响应结束********", chunk);
    });
  });
  req.on("error", function (err) {
    console.error(err);
  });

  req.end;
}

// http请求
export function gets(options: Object, callback: Function) {
  //创建请求
  let body = "";
  //   console.log("执行到底结束", options);
  let req = https.request(options, res => {
    res.setEncoding("utf-8");
    res.on("data", function (chunk) {
      // 解析unicode  编码
      chunk = unescape(
        chunk = unescape(
          chunk.replace(/\\u|\\"|\\|[\u4e00-\u9fa5]\'|[a-zA-Z]\'/g, w => {
            switch (w) {
              case "\\u": {
                return "%u";
                break;
              }
              case "\\": {
                return "";
                break;
              }
              case '\\"': {
                return '';
                break;
              }
              case "[\u4e00-\u9fa5]\'": {
                return "'";
                break;
              }
              case "[a-zA-Z]\'": {
                return "'";
                break;
              }

              default: {
                break;
              }
            }
          })));

      body += chunk;
    });
    res.on("end", function () {
      callback(JSON.parse(body));
      // callback(body)

      // console.log("响应结束********");
    });
  });
  req.on("error", function (err) {
    console.error(err);
  });

  req.end();
}
